/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
  CCell, Cell, Table, TableBody, TableRow, Text, TableHead, useTheme,
} from "customize-easy-ui-component";
import {DirectLink, Link as RouterLink} from "../../../routing/Link";
import {useFoldForList, useFoldGenerate, useSplitSubCapacity,} from "../../hook/useMainRepUrlOr";


//实际表5列 和才2列的：宽度可自己调节
const CLnPercents=[['12%',"%","60%"], ['9%',"%","41%","41%"],
                 ['6%',"%","28%","28%","28%"], ['6%',"%","22%","22%","22%","22%"]];
//pref!=null 拆分2栏目的情况；
/**@param where: 若3={id,name}对象形式的:安装单位、设计单位。若=1,若=2,
 * */
const CharacteristRow= (title:any,dlPage: any,field:string,rep: any,where?:number, pref?:any, span?:number
) => {
  return <TableRow >
    { pref? <><CCell rowSpan={span}>{pref}</CCell><CCell>{title}</CCell></>
        : pref===null? <CCell>{title}</CCell>
            : <CCell colSpan={2}>{title}</CCell>
    }
    { dlPage.map((p: any, c:number) =>{
        const text=where===1? p?.svp?.[field] :
            where===2? p?.pa?.[field] :
                where===3? p?.[field]?.name :
                    p?.[field];
        return  <DirectLink key={c} href={`/report/${rep?.modeltype}/ver/${rep?.modelversion}/${rep?.id}/Solidify?ppcode=`+p?.code+'#Solidify'}>
            <CCell key={c}>{text || '／'}</CCell>
          </DirectLink>
    }) }
  </TableRow>;
};
/**自带分项模式： 这不是内嵌式的有模板代码的公共模板的分项报告模式。
 * 正规jsx组件的用法需改成英文的。
 * 报错：Imported JSX component Moni监控管理系统 must be in PascalCase or SCREAMING_SNAKE_CASE ；<tag></tag>带儿子的组件名字不能用中文的。
 * */
export const PipelineCharacteristPla= ({ orc, rep, children,title} : { orc: any,rep: any,children?: React.ReactNode;title?:any}
) => {
  const theme= useTheme();
  //重组成二维 orc?.单元表?.=> 四个一页的组合。pages[ [1{单元},2,3,undefined ] , ]
  const pages= React.useMemo( () => {
    let pages: any[]=[];
    for(let f=0; f<orc?.单元表?.length; f+=4){
        pages.push( orc?.单元表?.slice(f,f+4) );
    }
    return pages;
  }, [orc?.单元表]);
  //一个折叠区：4*4 单元， 最多可能125页纸张，
  const lsBlockMax=useSplitSubCapacity(pages.length,4);
  const {sumArea, areaContent, btnBindUses}=useFoldForList(pages, lsBlockMax,false);
  const frCallback = (dlPage: any, arak:number, pid:number) => {
    const pn=arak * lsBlockMax;     //特性表第几张的 基数
    // console.log("特性表大度的 分页组=",dlPage,"pn=",pn,"arak=",arak,"pid=",pid);
    //注意dlPage：对特性表特别的：实际是1-4个的单元拼凑的对象形式集合[][]。
    const xsize=dlPage.length;
    let 检验员s: any[]=[];
    let hasMemos=false;
    for (const pp of dlPage) {
      if(pp?.sgm){
        const men =检验员s.find((m: any) => m.name === pp?.sgm.name);
        if(!men)  检验员s.push(pp?.sgm);
      }
      if(!hasMemos && pp?.mm)   hasMemos=true;
    }
    //因为特性表内容太多了，可能超过1张纸张了。【改规则】 最少也要显示3行的内容： 不强制新换1页；
    return <React.Fragment key={pid}>
      <div css={{"@media print": {paddingBottom: '6rem', pageBreakInside: 'avoid'}}}>
        <DirectLink href={`/report/${rep?.modeltype}/ver/${rep?.modelversion}/${rep?.id}/Solidify#Solidify`}>
          <Text variant="h2" css={{
            textAlign: 'center', marginTop: '1rem',
            "@media print": {
              //pageBreakBefore: 'always', marginTop: '1rem',
            },
          }}
          >{title ?? '压力管道数据表'}</Text>
        </DirectLink>
        <div css={{display: 'flex', justifyContent: 'flex-end',}}>
          <Text>报告编号：{rep.isp.no}</Text>
        </div>
      </div>
       <Table fixed={CLnPercents[xsize - 1]} css={{borderCollapse: 'collapse', "@media print": {marginTop: '-6rem'}
                  }} tight miniw={800}>
            <TableHead>
              <TableRow>
                <CCell colSpan={2}>项目 \ 序号</CCell>
                {dlPage.map((p: any, c: number) =>
                    <CCell key={c}><Text
                        id={`Characteristics${(pn + pid) * 4 + c}`}>{(pn + pid) * 4 + c + 1}</Text></CCell>
                )}
              </TableRow>
            </TableHead>
            <TableBody>
              {CharacteristRow('管道名称', dlPage, 'name', rep,)}
              {CharacteristRow('工程名称', dlPage, 'proj', rep,)}
              {CharacteristRow('管道编号', dlPage, 'code', rep,)}
              {CharacteristRow('管道级别', dlPage, 'level', rep,)}
              {CharacteristRow('外径 (mm)', dlPage, 'dia', rep, 0,)}
              {CharacteristRow(<Text css={{fontSize: 4===dlPage?.length? '0.8rem':theme.fontSizes[0]}}>公称直径(mm)</Text>, dlPage, '直径', rep, 1,)}
              {CharacteristRow(<Text css={{fontSize: 4===dlPage?.length? '0.8rem':theme.fontSizes[0]}}>公称壁厚(mm)</Text>, dlPage, 'thik', rep, 0,)}
              {CharacteristRow('管道长度(m)', dlPage, 'leng', rep, 0,)}
              {CharacteristRow('管道起点', dlPage, 'start', rep, 0,)}
              {CharacteristRow('管道止点', dlPage, 'stop', rep, 0,)}
              {CharacteristRow('设计单位', dlPage, 'desu', rep, 3,)}
              {CharacteristRow('安装单位', dlPage, 'insu', rep, 3,)}
              {CharacteristRow('安装日期', dlPage, 'insd', rep,)}
              {CharacteristRow('投用日期', dlPage, 'used', rep,)}
              {CharacteristRow('输送介质', dlPage, '工介', rep, 2)}
              {CharacteristRow('管道材料', dlPage, '材料', rep, 1)}
              {CharacteristRow(<Text css={{fontSize: 4===dlPage?.length? '0.785rem':theme.fontSizes[0]}}>设计压力(MPa)</Text>, dlPage,  '设压', rep, 1,)}
              {CharacteristRow(<Text css={{fontSize: 4===dlPage?.length? '0.785rem':theme.fontSizes[0]}}>操作压力(MPa)</Text>, dlPage, '工压', rep, 2,)}
              {CharacteristRow(<Text css={{fontSize: 4===dlPage?.length? '0.785rem':theme.fontSizes[0]}}>试验压力(MPa)</Text>, dlPage, '试压', rep, 2,)}
              {CharacteristRow(<Text css={{fontSize: 4===dlPage?.length? '0.8rem':theme.fontSizes[0]}}>设计温度(℃)</Text>, dlPage, '设温', rep, 1,)}
              {CharacteristRow(<Text css={{fontSize: 4===dlPage?.length? '0.8rem':theme.fontSizes[0]}}>操作温度(℃)</Text>, dlPage, '工温', rep, 2,)}
              {CharacteristRow(<Text css={{fontSize: 4===dlPage?.length? '0.8rem':theme.fontSizes[0]}}>腐蚀裕量(mm)</Text>, dlPage, '腐蚀', rep, 1)}
              {CharacteristRow('敷设方式', dlPage, 'lay', rep,)}
              {CharacteristRow('防腐层材料', dlPage, '防腐材', rep, 2)}
              {CharacteristRow(<Text css={{fontSize: 4===dlPage?.length? '0.74rem':theme.fontSizes[0]}}>防腐层沥青等级</Text>, dlPage, '沥青级', rep, 2)}
              {CharacteristRow(<Text css={{fontSize: 4===dlPage?.length? '0.725rem':theme.fontSizes[0]}}>防腐层厚度(mm)</Text>, dlPage, '防腐厚', rep, 2)}
              {/*{CharacteristRow('备注（图号）',dlPage,'图号',rep,2 )}*/}
              {CharacteristRow(<Text css={{fontSize: 4===dlPage?.length? '0.66rem':theme.fontSizes[0]}}>管道单元登记编码</Text>, dlPage, 'rno', rep,)}
            </TableBody>
          </Table>
          <Table fixed={["62%", "%"]} tight miniw={800}>
            <TableBody>
              <DirectLink href={`/report/${rep?.modeltype}/ver/${rep?.modelversion}/${rep?.id}/LineDiagram#LineDiagram`}>
                { hasMemos &&
                    <TableRow>
                      {/*这里备注实际是4个管道单元需分别做录入的。 然后这里合并显示*/}
                      <Cell colSpan={2}>
                        备注：&nbsp;
                        {dlPage.map((p: any, c: number) => p?.mm && <React.Fragment key={c}>
                          &nbsp;{p?.mm}。
                        </React.Fragment>)
                        }
                      </Cell>
                    </TableRow>
                }
                <TableRow>
                  <CCell>
                    <div css={{
                      height: '100%',
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignContent: 'space-between', alignItems: 'flex-start'
                    }}>
                      <div><Text>检验：</Text>
                        {检验员s.map((m: any, k: number) => <React.Fragment key={k}>
                          &nbsp;{m.name}
                        </React.Fragment>)
                        }
                      </div>
                      <div css={{textAlign: 'end'}}><Text>日期</Text>2022-12-31</div>
                    </div>
                  </CCell>
                  <CCell>
                    <div css={{
                      height: '100%',
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignContent: 'space-between',
                      alignItems: 'flex-start'
                    }}>
                      <div><Text>审核：</Text></div>
                      <div css={{textAlign: 'end'}}><Text>日期</Text>2021-01-31</div>
                    </div>
                  </CCell>
                </TableRow>
              </DirectLink>
            </TableBody>
          </Table>
    </React.Fragment>
  };

  const [renderAll]=useFoldGenerate({sumArea, btnBindUses, areaContent, callback: frCallback, mark: '特性表折叠'});

  return <>
      {pages.length <= 0 &&
          <RouterLink href={`/report/${rep?.modeltype}/ver/${rep?.modelversion}/${rep?.id}/Solidify#Solidify`}>
            <Text id='Solidify' variant="h2" css={{
              textAlign: 'center', marginTop: '1rem',
              "@media print": {display: 'none',},
            }}>管道特性表的单元选择</Text>
          </RouterLink>
      }
      <div id="Characteristics"></div>
      {renderAll}
      {children}
    </>
  ;
  };
